//
//  JourneyTableViewController.m
//  WildDonkey
//
//  Created by 佟小波 on 15/3/27.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "JourneyTableViewController.h"
#import "JourneyListTableViewCell.h"
#import "JourneyDetailTableViewController.h"
#import "JourneyDetailViewController.h"
#import "JourneyListData.h"
#import "AFNetworking.h"
#import "MJRefresh.h"
@interface JourneyTableViewController ()
//解析用属性
@property (nonatomic,retain) NSMutableDictionary *dictionary;
@property (nonatomic,retain) NSMutableArray *array;
@property (nonatomic,retain) NSMutableData *data;
@property (nonatomic,retain) NSMutableArray *DataArray;

//菊花
@property (nonatomic,retain) UIActivityIndicatorView *activityIndicator;

@property (nonatomic,assign) int refreshCount;

@end

@implementation JourneyTableViewController

- (void)dealloc
{
//	[_data release];
//	[_array release];
//	[_data release];
	[super dealloc];
}
#pragma mark touch
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//	[self.navigationController setNavigationBarHidden:YES animated:NO];
//	
//}

#pragma mark - 刷新

- (void)MJRefresh
{
	//下拉刷新
	[self.tableView addLegendHeaderWithRefreshingBlock:^{
		[self loadNewData];
	}];
//	
//	[self.tableView addLegendFooterWithRefreshingBlock:^{
//		[self loadNewData];
//	}];
	
	
	//进入刷新状态
	[self.tableView.legendHeader beginRefreshing];
	
}

//上拉刷新
- (void)loadNewDataFoot
{
	static int refreshCount = 0;
	[self loadDataStatrpos:refreshCount*20 eachpage:20];
	refreshCount += 1;

}

//下拉刷新数据
- (void)loadNewData
{
	[self loadDataStatrpos:0 eachpage:20];
	
	//刷新表格
	[self.tableView reloadData];
	
	//拿到当前下啦刷新的控件,结束刷新
	[self.tableView.header endRefreshing];
}

//图片加载菊花
- (void)loading
{
	_activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleWhiteLarge)];
	self.activityIndicator.frame = CGRectMake(self.view.center.x - 20, self.view.center.y - 40, 30, 30) ;
	self.activityIndicator.center = CGPointMake(self.view.center.x, self.view.center.y - 30);
	self.activityIndicator.color = [UIColor grayColor];
	[self.view addSubview:self.activityIndicator];
	[self.activityIndicator startAnimating];


}

//加载网络数据
- (void)loadDataStatrpos:(int)startpo eachpage:(int)eachpages
{
	NSString *startpos = [NSString stringWithFormat:@"%d",startpo];//向数据请求的数据列表开始位置
	NSString *eachpage = [NSString stringWithFormat:@"%d",eachpages];//每次请求的数据个数
	
	
	NSString *urlstr = [NSString stringWithFormat:@"http://mobileapp.roadqu.com/api/mobile/qunawan/travelnotes/alltravelnoteslist?startpos=%@&token=5444d64083242&smallpic=true&eachpage=%@",startpos,eachpage];
	//NSURL *url = [NSURL URLWithString:urlstr];
	
	AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
	
	[manager GET:urlstr parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
		NSLog(@"[JourneyTabelViewController]数据请求成功");
		
		//服务器数据总数
		self.dataCount = [responseObject valueForKey:@"count"];
		
		NSArray *array1 = [responseObject valueForKey:@"data"];
		
		self.array = [[NSMutableArray alloc] initWithCapacity:[array1 count]];
		
		for (NSDictionary *dic in array1) {
			JourneyListData *model = [[JourneyListData alloc] init];
			[model setValuesForKeysWithDictionary:dic];
			[self.array addObject:model];
			NSLog(@"%@",model);
			
			model = nil;
			[self.tableView reloadData];
			
		}
		NSLog(@"[JourneyTabelViewController]数据请求完毕");
	} failure:^(NSURLSessionDataTask *task, NSError *error) {
		NSLog(@"[JourneyTabelViewController]数据请求失败 %@",error);
		
	}];
}



- (void)viewDidLoad {
	[super viewDidLoad];
	
	[self MJRefresh];
	[self.tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
	
	self.navigationItem.title = @"游记";
	UIImageView *bgView = [[UIImageView alloc] init] ;
	bgView.image = [UIImage imageNamed:@"JourneyBG"];
	self.tableView.backgroundView = bgView;
	self.tableView.sectionIndexColor = [UIColor clearColor];
	
    self.refreshCount = 0 ;
	
	//[self.DataArray addObjectsFromArray:self.array];
	
	
	//网络请求数据  移至 loadData;
	/*
	 NSString *startpos = [NSString stringWithFormat:@"%d",self.refreshCount];//向数据请求的数据列表开始位置
	 NSString *eachpage = [NSString stringWithFormat:@"%d",20];//每次请求的数据个数
	 
	 
	 NSString *urlstr = [NSString stringWithFormat:@"http://mobileapp.roadqu.com/api/mobile/qunawan/travelnotes/alltravelnoteslist?startpos=%@&token=5444d64083242&smallpic=true&eachpage=%@",startpos,eachpage];
	 //NSURL *url = [NSURL URLWithString:urlstr];
	 
	 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
	 
	 [manager GET:urlstr parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
		NSLog(@"[JourneyTabelViewController]数据请求成功");
		
		//服务器数据总数
		self.dataCount = [responseObject valueForKey:@"count"];
	 
		NSArray *array1 = [responseObject valueForKey:@"data"];
		
		self.array = [[NSMutableArray alloc] initWithCapacity:[array1 count]];
		
		for (NSDictionary *dic in array1) {
	 JourneyListData *model = [[JourneyListData alloc] init];
	 [model setValuesForKeysWithDictionary:dic];
	 [self.array addObject:model];
	 NSLog(@"%@",model);
	 
	 model = nil;
	 [self.tableView reloadData];
	 
		}
		NSLog(@"[JourneyTabelViewController]数据请求完毕");
	 } failure:^(NSURLSessionDataTask *task, NSError *error) {
		NSLog(@"[JourneyTabelViewController]数据请求失败 %@",error);
	 
	 }];

	 */

	//ego 刷新  废弃
	/*
		 if (_refreshTableView == nil) {
		 //初始化下拉刷新控件
		 EGORefreshTableHeaderView *refreshView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];
		 refreshView.delegate = self;
		 //将下拉刷新控件作为子控件添加到UITableView中
		 [self.tableView addSubview:refreshView];
		 _refreshTableView = refreshView;
		 }

		 */
	
	//系统自带的网络请求 废弃
	/*
	 NSURL *url = [NSURL URLWithString:urlstr];
	 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:20];
	 
	 [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
	 
	 [request release];
	 request = nil;
	 */
	

	
	// Uncomment the following line to preserve selection between presentations.
	// self.clearsSelectionOnViewWillAppear = NO;
	
	// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
	// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

#pragma mark - 刷新 废弃
/*
//往上拉刷新
- (void)tailRefresh
{
	NSString *startpos = [NSString stringWithFormat:@"%d",20];//向数据请求的数据列表开始位置
	self.refreshCount = 0 ;
	NSString *eachpage = [NSString stringWithFormat:@"%d",20];//每次请求的数据个数
	
	
	NSString *urlstr = [NSString stringWithFormat:@"http://mobileapp.roadqu.com/api/mobile/qunawan/travelnotes/alltravelnoteslist?startpos=%@&token=5444d64083242&smallpic=true&eachpage=%@",startpos,eachpage];
	
	AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
	
	[manager GET:urlstr parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
		NSLog(@"[JourneyTabelViewController]数据请求成功");
		
		//服务器数据总数
		self.dataCount = [responseObject valueForKey:@"count"];
		
		NSArray *array1 = [responseObject valueForKey:@"data"];
		
		self.array = [[NSMutableArray alloc] initWithCapacity:[array1 count]];
		
		for (NSDictionary *dic in array1) {
			JourneyListData *model = [[JourneyListData alloc] init];
			[model setValuesForKeysWithDictionary:dic];
			[self.array addObject:model];
			NSLog(@"%@",model);
			
			model = nil;
			[self.tableView reloadData];
			
		}
		NSLog(@"[JourneyTabelViewController]数据刷新完毕");
	} failure:^(NSURLSessionDataTask *task, NSError *error) {
		NSLog(@"[JourneyTabelViewController]数据刷新失败 %@",error);
		
	}];

}

#pragma mark Data Source Loading / Reloading Methods
//开始重新加载时调用的方法
- (void)reloadTableViewDataSource{
	_reloading = YES;
	//开始刷新后执行后台线程，在此之前可以开启HUD或其他对UI进行阻塞
	[NSThread detachNewThreadSelector:@selector( tailRefresh) toTarget:self withObject:nil];
}

//完成加载时调用的方法
- (void)doneLoadingTableViewData{
	NSLog(@"doneLoadingTableViewData");
	
	_reloading = NO;
	[_refreshTableView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
	//刷新表格内容
	[self.tableView reloadData];
}

#pragma mark EGORefreshTableHeaderDelegate Methods
//下拉被触发调用的委托方法
-(void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view
{
	[self reloadTableViewDataSource];
}

//返回当前是刷新还是无刷新状态
-(BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view
{
	return _reloading;
}

//返回刷新时间的回调方法
-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view
{
	return [NSDate date];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods
//滚动控件的委托方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
	[_refreshTableView egoRefreshScrollViewDidScroll:scrollView];
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
	[_refreshTableView egoRefreshScrollViewDidEndDragging:scrollView];
}
*/
#pragma mark - Connection delegate 废弃

/*
 //接到回应
 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
 {
	self.data = [NSMutableData data];
 }
 
 //服务器多次返回的数据;
 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
 {
	[self.data appendData:data];
 }
 
 //下载完成之后
 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
 {
	NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:self.data options:(NSJSONReadingMutableLeaves) error:nil];
	
	NSArray *array1 = [dic1 valueForKey:@"data"];
	
 //	NSLog(@"%@",array1);//测试正常
 
	self.array = [[NSMutableArray alloc] initWithCapacity:[array1 count]];
	
 //	NSLog(@"%ld",[array1 count]);//测试正常
 
	for (NSDictionary *tempDic in array1) {
 JourneyListData *tempData = [[JourneyListData alloc] init];
 [tempData setValuesForKeysWithDictionary:tempDic];
 [self.array addObject:tempData];
 
 
 
 //		[tempData release];
 
	}
 //	NSLog(@"_________________________________________");
 //	JourneyListData *r = self.array[1];
 //	NSLog(@"%@",r.img);//测试正常
 
	
	
	
 }
 
 //错误,超时之后执行
 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
 {
	NSLog(@"游记列表数据请求出错 :%@",error);
 
 }

 */

#pragma mark - Table view data source

//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 150;
}

//分区头高度
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section
{
	return 0;
}

//顶部header视图;
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	
	return nil;
}

//分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
	// Return the number of sections.
	return 1;
}

- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section
{
	NSLog(@"xxx");
	
}
//分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
	// Return the number of rows in the section.
//	return [self.array count];
	return [self.array count];
}

//cell 的样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	//防止数组越界
	JourneyListData *dateIndexpath = nil;
	if (indexPath.row < [self.array count]) {
		dateIndexpath = self.array[indexPath.row];
	}
	
	
	static NSString *cellIdentIfier = @"tours";
	
	JourneyListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentIfier];
	if (nil == cell) {
		cell = [[JourneyListTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:cellIdentIfier];
	}
	cell.backgroundColor = [UIColor clearColor];
	cell.data = dateIndexpath;
	
	
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	return cell;
}

//选中行执行操作;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	JourneyDetailViewController *detailVC = [[JourneyDetailViewController alloc] init] ;
	
	//传值
	//防止数组越界
	JourneyListData *dateIndexpath = nil;
	if (indexPath.row < [self.array count]) {
		dateIndexpath = self.array[indexPath.row];
	}

	detailVC.yid = dateIndexpath.yid;
	//detailVC.title = dateIndexpath.title;
	
	
	//push 到下一级页面
	[self.navigationController pushViewController:detailVC animated:YES];
//	[detailVC release];
//	detailVC = nil;
	
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
